//
//  CategoryListViewController.m
//  ChunLaiZhuangClient
//
//  Created by zzs on 16/4/10.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "CategoryListViewController.h"
#import "HeadSearchTableViewCell.h"
#import "ProductListsTableViewCell.h"
#import "ProdcutListCategoryModel.h"
#import "FirstCategoryModel.h"
@interface CategoryListViewController (){
    ProdcutListCategoryModel *categoryModel;  //产品数据
    SINavigationMenuView *menu;
    NSMutableArray *productsArray;  //数据源
    BOOL isLayoutViews; //是否布局上面的子视图
    NSArray *subClassArray; //小图片的数据集合
    BOOL isHaveSamllView;//是否有顶部的小视图
   
    
}
@property(nonatomic,strong)UIScrollView *scrollCategoryView;
@property(nonatomic,strong) FirstCategoryModel *firstCategoryModel;  //一级分类
@property(nonatomic,assign) int pageNum; //页数
@property(nonatomic,copy)NSString *order; //升降序
@end

@implementation CategoryListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageNum=1;
    self.order=@"DESC";
    isLayoutViews=YES;
    isHaveSamllView=NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    //[self layoutSubViwsInScrollow:self.dataModel.classArray];
    [self addRightItem];
    [self setNaviLeftButton:@""];
    [self loadFirstCategoryData];
    productsArray=[[NSMutableArray alloc] init];
    // Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
#pragma mark-顶部滑动的分类
-(UIScrollView*)scrollCategoryView{
    if (!_scrollCategoryView) {
        _scrollCategoryView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,88)];
        _scrollCategoryView.backgroundColor=[UIColor whiteColor];
}
    return _scrollCategoryView;
}
#pragma mark-布局上面小视图
-(void)layoutSubViwsInScrollow:(NSArray*)dataArray{
    if (![self.view.subviews containsObject:self.scrollCategoryView]) {
        [self.view addSubview:self.scrollCategoryView];

    }
    subClassArray=dataArray;
    for(UIView *subview in _scrollCategoryView.subviews){
        [subview removeFromSuperview];
    }
    _scrollCategoryView.contentSize=CGSizeMake(11+(70+9)*dataArray.count+70, 88);
    for (int i=0; i<dataArray.count; i++) {
        SubcategoryModel *model=dataArray[i];
        UIButton *categoryBt=[UIButton buttonWithType:UIButtonTypeCustom];
        categoryBt.tag=i;
        [categoryBt setTitle:model.name forState:UIControlStateNormal];
        categoryBt.titleLabel.font=[UIFont systemFontOfSize:14];
        [categoryBt sd_setBackgroundImageWithURL:[NSURL URLWithString:model.image] forState:UIControlStateNormal placeholderImage:nil];
        categoryBt.titleEdgeInsets=UIEdgeInsetsMake(35, 0, 0, 0);
        categoryBt.frame=CGRectMake(11+(70+9)*i, 6, 70, 70);
        categoryBt.layer.cornerRadius=4;
        categoryBt.clipsToBounds=YES;
        [categoryBt addTarget:self action:@selector(categoryAction:) forControlEvents:UIControlEventTouchUpInside];
        [_scrollCategoryView addSubview:categoryBt];
    }   
}
#pragma mark-点击小图片
-(void)categoryAction:(UIButton*)bt{
    SubcategoryModel *model=subClassArray[bt.tag];
    self.pageNum=1;
    [self loadProductData:model.category_id];
    
}
-(void)addDropMenuView{
    if (self.navigationItem) {
        CGRect frame = CGRectMake(0.0, 0.0, 150.0, self.navigationController.navigationBar.bounds.size.height);
        FirstCategorySubModel *subModel=_firstCategoryModel.data;
        NSMutableArray *menuArray=[[NSMutableArray alloc] init];
        for (int i=0; i<subModel.categories.count; i++) {
            SubcategoryModel *detailModel=subModel.categories[i];
            [menuArray addObject:detailModel.name];
        }
        menu = [[SINavigationMenuView alloc] initWithFrame:frame title:self.navTitle];
        [menu displayMenuInView:self.navigationController.view];
        menu.items =menuArray;
        menu.delegate = self;
        self.navigationItem.titleView = menu;
    }

}
-(void)addRightItem{
    UIButton *cancelBt=[UIButton buttonWithType:UIButtonTypeCustom];
    cancelBt.frame=CGRectMake(0,25, 64, 35);
    [cancelBt setTitle:@"价格" forState:UIControlStateNormal];
    [cancelBt setImage:[UIImage imageNamed:@"icon_price_low"] forState:UIControlStateNormal];
    [cancelBt setImage:[UIImage imageNamed:@"icon_price_high"] forState:UIControlStateSelected];
    [cancelBt setImageEdgeInsets:UIEdgeInsetsMake(0, 55, 0, 0)];
    cancelBt.titleLabel.font=[UIFont systemFontOfSize:15];
    [cancelBt setTitleColor:[UIColor colorWithHexString:@"000000"] forState:UIControlStateNormal];
    [cancelBt addTarget:self action:@selector(priceAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:cancelBt];
}
-(void)loadFirstCategoryData{
     [[LKDHud shareHud] showLoadingView];
    __weak typeof (self) weakSelf = self;
    [ApiClient getAllFirstCategoriesDidFinishLoaded:^(FirstCategoryModel *model, NSString *path) {
         [[LKDHud shareHud] hideLoadingView];
        weakSelf.firstCategoryModel=model;
        [self addDropMenuView];
        if (_dataModel) {
            if (self.subcategoryModel) {
                [self loadProductData:self.subcategoryModel.category_id];
            }else{
               [self loadProductData:_dataModel.CategoryID];
            }
        }else{
            if (self.linkID) {
              [self loadProductData:self.linkID];
            }
           
        }
       
    } didFailLoaded:^(NSError *error, NSString *path) {
         [[LKDHud shareHud] hideLoadingView];
        
    }];

}
-(void)loadProductData:(NSString*)categoryID{
    __weak typeof (self) weakSelf = self;
     [[LKDHud shareHud] showLoadingView];
    [ApiClient getProductListCategory_id:categoryID sort:@"price" order:self.order page:[NSString stringWithFormat:@"%d",self.pageNum] didFinishLoaded:^(ProdcutListCategoryModel *model, NSString *path) {
         [[LKDHud shareHud] hideLoadingView];
        categoryModel=model;
        if (weakSelf.pageNum==1) {
          [productsArray removeAllObjects];
        }
        if (model.data.total_page.integerValue<=1) {
            self.displayView.mj_footer.hidden=YES;
            
        }else{
            self.displayView.mj_footer.hidden=NO;
        }
        [productsArray addObjectsFromArray:categoryModel.data.products];
        categoryModel.data.products=productsArray;
        //重新布局子视图
        if (isLayoutViews) {
            if (categoryModel.data.subcategories.count>0 ||isHaveSamllView) {
                [weakSelf layoutSubViwsInScrollow:categoryModel.data.subcategories];
                isLayoutViews=NO;
                isHaveSamllView=YES;
            }
         
        }
        if (![self.view.subviews containsObject:self.displayView]) {
            [self.view addSubview:self.displayView];
        }
        [self.displayView reloadData];
        if (categoryModel.data.subcategories.count==0 &&!isHaveSamllView) {
            self.scrollCategoryView.hidden=YES;
            self.displayView.top=0;
            self.displayView.height=SCREEN_HEIGHT-64;
        }else{
            self.scrollCategoryView.hidden=NO;
            self.displayView.top=88;
            self.displayView.height=SCREEN_HEIGHT-64-88;

        }
        //结束下拉刷新和加载更多状态
         [weakSelf.displayView.mj_header endRefreshing];
        if (model.data.total_page.integerValue == self.pageNum) {
            [self.displayView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.displayView.mj_footer endRefreshing];
        }
        
        
    } didFailLoaded:^(NSError *error, NSString *path) {
         [[LKDHud shareHud] hideLoadingView];
        [weakSelf.displayView.mj_header endRefreshing];
         [weakSelf.displayView.mj_footer endRefreshing];
    }];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    menu.menuButton.isActive=NO;
    [menu onHandleMenuTap:nil];
}
#pragma mark-按价格排序
-(void)priceAction:(UIButton*)bt{
    bt.selected=!bt.selected;
    if (bt.selected) {
      self.order=@"ASC";
    }else{
      self.order=@"DESC";
    }
    self.pageNum=1;
    if (_dataModel) {
        if (self.subcategoryModel) {
            [self loadProductData:self.subcategoryModel.category_id];
        }else{
            [self loadProductData:_dataModel.CategoryID];
        }
    }else{
        if (self.linkID) {
            [self loadProductData:self.linkID];
        }
        
    }

   
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(UITableView*)displayView{
    if (!_displayView) {
        __weak typeof(self) weakSelf = self;
        _displayView=[[UITableView alloc] initWithFrame:CGRectMake(0,88, SCREEN_WIDTH, SCREEN_HEIGHT-64-88)];
        _displayView.delegate=self;
        _displayView.dataSource=self;
        _displayView.backgroundColor=[UIColor clearColor];
        _displayView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _displayView.mj_header = [CLZRefreshHeader headerWithRefreshingBlock:^{
            weakSelf.pageNum=1;
            if (_dataModel) {
                if (self.subcategoryModel) {
                    [self loadProductData:self.subcategoryModel.category_id];
                }else{
                    [self loadProductData:_dataModel.CategoryID];
                }
            }else{
                if (self.linkID) {
                    [self loadProductData:self.linkID];
                }
                
            }


        }];
        
        _displayView.mj_footer = [CLZRefreshFooter footerWithRefreshingBlock:^{
            self.pageNum++;
            if (_dataModel) {
                if (self.subcategoryModel) {
                    [self loadProductData:self.subcategoryModel.category_id];
                }else{
                    [self loadProductData:_dataModel.CategoryID];
                }
            }else{
                if (self.linkID) {
                    [self loadProductData:self.linkID];
                }
                
            }
            
        }];


    }
    return _displayView;
}
#pragma mark-UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            HeadSearchTableViewCell *cell=[HeadSearchTableViewCell cellWithTableView:tableView];
            return cell;
        }
            break;
        case 1:
        {
            if (categoryModel.data.products.count>0) {
                ProductListsTableViewCell *cell=[ProductListsTableViewCell cellWithTableView:tableView];
                [cell setCategoryModel:categoryModel.data];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                return cell;

            }else{
                QLKEmptyCellTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kEmptyCellTableViewCellIdentify];
                if (!cell) {
                    cell = [[QLKEmptyCellTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kEmptyCellTableViewCellIdentify];
                }
                [cell setLogoImage: @"fw_icon_no_content" cellHeight:self.displayView.height];
                cell.titleLabel.text = @"暂无相关内容" ;
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                return cell;
 
            }
        }
            break;
    
        default:
            return nil;
            break;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
            return 45;
            break;
        case 1:
        {
            if (categoryModel.data.products.count>0) {
                int count=categoryModel.data.products.count;
                int lineNum=0;
                if (count%2==0) {
                    lineNum=count/2;
                }else{
                    lineNum=count/2+1;
                }
                
                return lineNum*240;
            }else{
                return tableView.height-45;
            }
            

        }
            break;
  
        default:
            return 0;
            break;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0, 0, 0)];
    }
    
}
-(void)viewDidLayoutSubviews
{
    if ([self.displayView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.displayView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.displayView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.displayView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}
- (void)didSelectItemAtIndex:(NSUInteger)index
{
    FirstCategorySubModel *subModel=_firstCategoryModel.data;
    SubcategoryModel *detail=subModel.categories[index];
    menu.menuButton.title.text=detail.name;
    self.linkID=detail.category_id;
    isLayoutViews=YES;
    self.pageNum=1;
    [self loadProductData:self.linkID];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
